import React from 'react';
import { Popup, Modal, Toast, InputItem, WhiteSpace, Button, WingBlank, Flex } from 'antd-mobile';
import { createForm } from 'rc-form';
import ReactDOM from 'react-dom';
import { Helmet } from "react-helmet";
import _ from 'lodash';
import moment from 'moment';
import Container from '../components/Base/Container';
import { hashHistory } from "react-router";
import {
  fetchCouponCode,
  bindVipCard,
  vipEdit,
  reg,
  regNew,
  fetchVipCardInfo,
  fetchVerifyCode,
  findVipCardNo,
  fetchVipConsume,
  fetchVipAcc,
  fetchShopWechat,
  fetchJc,
  fetchSavelist,
  fetchStored,
  createConsumeFeedback,
  getWheelStatus,
  getOpenidByCode,
  findVipByOpenid,
  fetchVipTypes,
  fetchVipCardBranch,
  fetchVipMyAcc,
  fetchVipType,
  fetchVipCard,
  fetchConvertAcc,
  fetchConsume,
} from '../services/vipService';
import * as imService from '../services/imService';
import VipShopShow from '../components/Base/VipShopShow';
import styles from './vipCard.less';
import CardSelector from './components/CardSelector';
import VipRegForm from './components/VipRegForm';
import VipEditForm from './components/VipEditForm';
import VipRights from './components/VipRights';
import CouponCode from '../components/Base/CouponCode';
import VipBarcode from '../components/Base/VipBarcode';
import IconItem from './components/IconItem';
import ConsumeFeedback from './components/ConsumeFeedback';
import VipAccList from './components/VipAccList';
import ChatMessage from '../components/im/ChatMessage';
import VipMyAcc from './components/VipMyAcc'
import VipInvite from '../routes/VipInvite'
import * as util from './util';
import * as paidVipUtil from '../utils/paidVip'

const testShopIds = ['sixun_000032'];
const isTestShop = shopId => _.includes(testShopIds, shopId);
const defaultDistance = 99999999999999999999999999999999999999999999999;
const map = new BMap.Map();

if (/Android/gi.test(navigator.userAgent)) {
  window.addEventListener('resize', () => {
    if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') {
      window.setTimeout(() => {
        document.activeElement.scrollIntoViewIfNeeded();
      }, 0);
    }
  });
}

// fix touch to scroll background page on iOS
// https://github.com/ant-design/ant-design-mobile/issues/307
// https://github.com/ant-design/ant-design-mobile/issues/163
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let maskProps;
if (isIPhone) {
  // Note: the popup content will not scroll.
  maskProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

// local storage key
const CARD_NO = 'qez_vip_card_no'; // 卡号
const CARD_NO_EXPIRE = 'qez_vip_card_no_expire'; // 过期卡号
const CARD_EXPIRATION = 'qez_vip_card_expiration'; // 卡号过期天数
const CARD_BIND_DATE = 'qez_vip_card_bind_date'; // 卡绑定时间
const CARD_OPENID = 'qez_xfdsfainvienslnv';     // openid
const CARD_REG_SALE_ID = 'qez_vip_reg_saleman_id';
const CARD_REG_BRANCH_NO = 'qez_vip_reg_branch_no';

// 本地路由
const ROUTE_BARCODE = 'barcode';
const ROUTE_COUPON = 'coupon';
const ROUTE_REG = 'reg';
const ROUTE_RIGHTS = 'rights';
const ROUTE_FEEDBACK = 'feedback';
const ROUTE_IM = 'im';
const ROUTE_ACC = 'acc';
const ROUTE_XIAO_FEI = 'xiaofeijilu';     //消费记录
const URL_ROUTE_LIST = [ROUTE_FEEDBACK, ROUTE_REG]; // 由url传入的本地路由
const LOCAL_ROUTE = 'localRoute';
const ROUTE_AI = 'ai';
const ROUTE_MYACC = 'myacc'; // 我的积分

class VipCard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      vipRights: [], // 会员权益
      vipType: [], // 会员等级
      timer: 0,
      timeLimit: 0,
      isBind: false,
      card_no: '',
      card_id: '',
      vipConsume: [],
      vipAcc: { remain_acc: 0 },
      vipInfo: {},
      vipCardInfo: {},
      branchList: [],
      loading: false,
      regLoading: false,
      couponCodeNum: 0,
      card_type: '',
      showExtraInfo: true,
      extraInfo: {
        savelist: 0,
        jc: 0,
        stored: 0,
      },
      route: '',
      imSender: null,
      imTarget: null,
      imMessages: [],
      newImFlag: false,
      
      /* 抽奖状态 */
      wheelStatus: false,
      wheelDot: false,

      openid: '',

      cardType: [],
      shopName: '',
      regSalemanId: '',
      regBranchNo: '',
      ConvertAcc: {}
    };
  }


  // --- 本地缓存：localstorage和cookie 代码 start --- /
  fetchCacheKey(name, old) {
    if (old) {
      return name;
    }
    const shopId = this.props.location.query.shopId;
    return `${name}_${shopId}`;
  }

  getLocalCache = (name, old) => {
    const keyName = this.fetchCacheKey(name, old);
    let result = util.getCookie(keyName) || window.localStorage.getItem(keyName);
    switch (name) {
      case CARD_NO:
      case CARD_NO_EXPIRE:
        result = result ? JSON.parse(result) : result;
        break;
      case CARD_EXPIRATION:
        result = result ? +result : result;
        break;
      default:
        break;
    }
    return result;
  };

  removeLocalCache = (name, old) => {
    const keyName = this.fetchCacheKey(name, old);
    util.setCookie(keyName, '');
    window.localStorage.removeItem(keyName);
  };

  setLocalCache = (name, data) => {
    if (data === null || data === undefined) {
      return;
    }
    data = _.isObject(data) ? JSON.stringify(data) : data;
    const keyName = this.fetchCacheKey(name);
    util.setCookie(keyName, data);
    window.localStorage.removeItem(keyName);
    window.localStorage.setItem(keyName, data);
  };

  migrateLocalCache = () => {
    // 将老版本的本地缓存的key添加shopId
    if (this.getLocalCache(CARD_NO, true)) {
      this.setLocalCache(CARD_NO, this.getLocalCache(CARD_NO, true));
      this.setLocalCache(CARD_NO_EXPIRE, this.getLocalCache(CARD_NO_EXPIRE, true));
      this.setLocalCache(CARD_BIND_DATE, this.getLocalCache(CARD_BIND_DATE, true));
      this.setLocalCache(CARD_EXPIRATION, this.getLocalCache(CARD_EXPIRATION, true));

      this.removeLocalCache(CARD_NO, true);
      this.removeLocalCache(CARD_NO_EXPIRE, true);
      this.removeLocalCache(CARD_BIND_DATE, true);
      this.removeLocalCache(CARD_EXPIRATION, true);
    }
  };

  getExpiration = () => {
    const v = this.getLocalCache(CARD_EXPIRATION);
    return v ? +v : v;
  };

  setExpiration = (num = 0) => {
    this.setLocalCache(CARD_EXPIRATION, num);
  };

  clearExpiration = () => {
    this.removeLocalCache(CARD_EXPIRATION);
  };

  getBindDate = () => {
    return this.getLocalCache(CARD_BIND_DATE);
  };

  setBindDate = () => {
    const date = moment().format();
    this.setLocalCache(CARD_BIND_DATE, date);
    return date;
  };
  // --- 本地缓存：localstorage和cookie 代码 end --- /


  getVipType = async () => {
    const shopId = this.props.location.query.shopId
    let res = await fetchVipType(shopId)
    this.setState({
      vipType: res.data
    })
  }
  getVipRights = async () => {
    const shopId = this.props.location.query.shopId
    let res = await fetchVipCard(shopId)
    this.setState({
      vipRights: res.data
    })
  }
  getConvertAcc = async () => {
     const shopId = this.props.location.query.shopId
     let res = await fetchConvertAcc(shopId, 100)
     this.setState({
      ConvertAcc: res
     })
  }
  getConsume = async () => {
    const {shopId} = this.props.location.query
    const card_id = '18476525018'
    let res = await fetchConsume(shopId, card_id)
    console.log('新消费记录', res)
  }

  componentDidMount() {
    Toast.loading('请稍候...', 5);
    this.getVipType()
    this.getVipRights()
    this.getConvertAcc()
    this.getConsume()

    this.setupSalemanReg();
    this.migrateLocalCache(); // 迁移旧的没有shopId的缓存key
    this.setupVipCardInfo(this.props.location.query.shopId); // 查询门店Vip卡设置
    this.onRegVip(false);

    const success = this.setupByCache();
    if (!success) {
      this.setupByWechat();
      this.setupLocalRoute();
    } else {
      setTimeout(() => {
        Toast.hide();
      }, 500);
    }
  }

  componentWillUnmount() {
    clearInterval(this.state.timer);
  }

  // 导购扫码注册
  setupSalemanReg = () => {
    let regSalemanId = this.props.location.query.regSalemanId;
    let regBranchNo = this.props.location.query.regBranchNo;
    if (regSalemanId) {
      this.setLocalCache(CARD_REG_SALE_ID, regSalemanId);
    }
    if (regBranchNo) {
      this.setLocalCache(CARD_REG_BRANCH_NO, regBranchNo);
    }

    const localRoute = this.props.location.query.localRoute;
    if (localRoute && localRoute == ROUTE_REG) {
      regSalemanId = regSalemanId || this.getLocalCache(CARD_REG_SALE_ID);
      regBranchNo = regBranchNo || this.getLocalCache(CARD_REG_BRANCH_NO);
      this.setState({
        regSalemanId,
        regBranchNo,
      });
    }
  }

  setupAll = (vip) => {
    // this.setupVipInfo(vip);
    this.setupLocalRoute();
    this.setupVipState(vip.shopId, vip.card_id, vip);
    this.setupVipCard(vip);

    this.setupExtraInfo(vip);
    this.setupIM(vip);

    this.setupBigWheel();

    this.setupCoupon(vip);

    Toast.hide();
  }

  setupByCache = () => {
    let result = false;
    const vip = this.getLocalCache(CARD_NO);
    if (vip && vip.card_id) {
      this.setupAll(vip);
      result = true;
    }
    return result;
  };

  setupByOpenid = (openid, shopId) => {
    findVipByOpenid(openid, shopId).then((res) => {
      if (res.data.success === true) {
        const { vip } = res.data;
        if (!_.isObject(vip)) {
          return;
        }
        this.saveVip(vip);
        this.setupAll(vip);
      }
    });
  }

  loadOpenidByCode = (code, shopId) => {
    getOpenidByCode(code, shopId).then((res) => {
      if (res.data.success === true) {
        const openid = res.data.openid;
        if (openid) {
          this.setLocalCache(CARD_OPENID, openid);
          this.setupByOpenid(openid, shopId);
          this.setState({
            openid,
          });
        }
      }
    });
  }

  preGetOpenid = (shopId) => {
    fetchShopWechat(shopId).then((data) => {
      // 门店主后台设置微信appid/appsecert才跳转
      if (data.data && data.data.appId) {
        // 微信redirect_uri中不能出现hash，需要后台重定向
        const redirectUri = encodeURI("http://wx.hy-bang.com/wx/oauthRedirect");
        const stateData = { host: window.location.host, shopId };
        const regSalemanId = this.props.location.query.regSalemanId;
        if (regSalemanId) {
          stateData.reg = true;
        }
        const state = JSON.stringify(stateData);
        const scope = 'snsapi_base';
        const timestamp = (new Date()).getTime();
        const oauthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${data.data.appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}&v=${timestamp}#wechat_redirect`;
        window.location.href = oauthUrl;
      } else {
        setTimeout(() => {
          this.setupByCache();
          Toast.hide();
        }, 100);
      }
    }).catch((e) => {
      console.error('preGetOpenid fetchShopWechat', { error: e });
    });
  }

  setupByWechat() {
    let openid = this.getLocalCache(CARD_OPENID);
    const code = this.props.location.query.code;
    const shopId = this.props.location.query.shopId;

    if (_.isString(openid) && openid.length > 0) {
      openid = openid.trim();
      this.setState({
        openid,
      });
    }

    if (_.isString(code) && code.length > 0) {
      this.loadOpenidByCode(code, shopId);
      return;
    }

    if (_.isString(openid) && openid.length > 0 && _.toUpper(openid) !== "NULL") {
      this.setupByOpenid(openid, shopId);
      this.setState({
        openid,
      });
      return;
    }

    const debugMode = !!this.props.location.query.__debug;
    if (debugMode || util.isLocal()) {
      Toast.hide();
      Modal.alert('跳转微信登录？', '检测到本地或开发环境', [
        {
          text: '取消',
          onPress: () => {
            console.log('cancel');
            // this.setState({
            //   openid: 'testopenid',
            // });
          },
        },
        { text: '确定', onPress: () => this.preGetOpenid(shopId) },
      ]);
    } else {
      this.preGetOpenid(shopId);
    }
  }

  setupBigWheel = () => {
    //大转盘
    const shopId = this.props.location.query.shopId;
    const card_id = this.state.card_id;

    getWheelStatus(shopId, card_id).then((res) => {
      console.log('大转盘', res)
      if (res.data.success === true && res.data.data) {
        const status = res.data.data.status;
        const times = res.data.times;

        this.setState({
          wheelStatus: status,
          wheelDot: times > 0,
        });
      }
    });
  }

  // setupVipInfo = (vip) => {
  //   this.setState({
  //     isBind: !!vip,
  //     card_no: vip ? vip.card_no : '',
  //     card_id: vip ? vip.card_id : '',
  //     card_type: vip ? vip.card_type : '',
  //     vipInfo: vip || {},
  //   });
  // }

  setupLocalRoute = () => {
    const route = this.props.location.query[LOCAL_ROUTE];
    if (route && _.includes(URL_ROUTE_LIST, route)) {
      this.setState({
        route,
      });
    }
    const [head, tail] = window.location.href.split('?');
    window.location.href = head + '?' + tail.split('&').filter(p => !p.startsWith(LOCAL_ROUTE + '=')).join('&');
  };

  setupIM = (vip) => {
    const { shopId, saleman_id, card_no, card_id } = vip;
    imService.fetchVipImUser(shopId, card_id || card_no).then((vipResult) => {
      const vipImUser = vipResult.data;
      if (vipImUser) {
        this.setState({
          imSender: vipImUser,
        });
      }

      setTimeout(() => {
        const salemanId = this.state.saleman_id || saleman_id;
        if (salemanId) {
          imService.fetchSalemanImUser(shopId, salemanId).then((salemanResult) => {
            const salemanImUser = salemanResult.data;
            if (salemanImUser) {
              this.setState({
                imTarget: salemanImUser,
              });
            }
            if (vipImUser && salemanImUser) {
              imService.fetchImMessages(shopId, {
                filter: {
                  $or: [
                    {
                      senderId: vipImUser.userId,
                      targetId: salemanImUser.userId,
                    },
                    {
                      targetId: vipImUser.userId,
                      senderId: salemanImUser.userId,
                    },
                  ],
                },
                sort: { sendTime: -1 },
              }).then((result) => {
                if (result && result.data) {
                  this.setState({
                    imMessages: _.reverse(result.data),
                  });
                }
                setTimeout(() => {
                  imService.initIMClient(vipImUser.imToken, (type, content, message) => {
                    const { imMessages } = this.state;
                    const newMessage = {
                      type,
                      senderId: message.senderUserId,
                      targetId: salemanImUser.userId,
                      content,
                    };
                    const newImFlag = this.state.route !== ROUTE_IM;
                    this.setState({
                      imMessages: [...imMessages, newMessage],
                      newImFlag,
                    });
                  }).then((imResult) => {
                    if (imResult) {
                      console.error('initIMClient', imResult);
                    }
                  });
                }, 200);
              });
            }
          });
        }
      }, 2500);
    });
  }

  onSendIM = (type, content) => {
    if (type && content) {
      const { imSender, imTarget } = this.state;
      imService.createImMessage(imSender.shopId, {
        type,
        content,
        senderId: imSender.userId,
        targetId: imTarget.userId,
      }).then((result) => {
        if (result && result.data) {
          const { imMessages } = this.state;
          this.setState({
            imMessages: [...imMessages, result.data],
          });
        }
      });
    }
  }

  setupVipCard = (localVip) => {
    // 检测后台绑卡状态
    findVipCardNo(localVip.shopId, localVip.mobile || localVip.vip_tel || localVip.phone, localVip.card_no, localVip.card_id).then((data) => {
      const remoteVips = data.data.vips;
      console.log('检测后台绑卡状态', data)
      if (remoteVips && remoteVips.length > 0) {
        const remoteVip = _.find(remoteVips, (vip) => {
          return (vip.card_id === localVip.card_id || vip.card_no === localVip.card_no);
        });

        if (!remoteVip) {
          Toast.fail('会员卡状态异常，请通知门店服务人员，15秒后将返回绑卡页面', 15, () => {
            this.handleDestroyBind(true);
          });
          return;
        }

        // 1. 查询本卡的 card_bind_status 是否为 false，是就解绑当前卡
        if (remoteVip.card_bind_status === false) {
          Toast.success('会员卡已经被解绑，准备刷新...', 3);
          setTimeout(() => {
            this.handleDestroyBind(true);
          }, 500);
          return;
        }

        // 2. 检查 saleman_id, card_no 变化
        if (remoteVip.card_bind_status === true && remoteVip.saleman_id && remoteVip.saleman_id !== localVip.saleman_id) {
          this.setState({
            saleman_id: remoteVip.saleman_id,
          });
        }
        if (remoteVip.card_bind_status === true && remoteVip.card_no && remoteVip.card_no !== localVip.card_no) {
          this.setState({
            card_no: remoteVip.card_no,
          });
        }

        // 3. 检查当前卡 card_bind_status hyb_openid 是否不存在，是的话就发送绑卡请求
        if (remoteVip && (_.includes([null, undefined, ''], remoteVip.card_bind_status) || _.includes([null, undefined, ''], remoteVip.hyb_openid))) {
          let hyb_openid = this.state.openid || this.getLocalCache(CARD_OPENID);
          if (!hyb_openid || !hyb_openid.length || _.toUpper(hyb_openid) === 'NULL') {
            hyb_openid = '';
          }
          bindVipCard({
            shopId: localVip.shopId,
            card_id: localVip.card_id,
            card_no: localVip.card_no,
            card_bind_status: true,
            hyb_openid,
          }).then((result) => {
            console.info('绑卡状态写入成功');
          }, (error) => {
            console.error('绑卡状态写入失败', JSON.stringify(error));
          });
        }

        // 获取最新的 card_type
        this.setState({
          card_type: _.trim(remoteVip.card_type),
        });

        this.setState({
          shopName: remoteVip.shopName,
        });

        if (_.isString(remoteVip.shopName) && _.isString(remoteVip.branch_name)) {
          document.title = remoteVip.shopName;
        }

        // 检查会员资料完整性
        setTimeout(() => {
          this.checkVipCompleteness(remoteVip);
        }, 2000);
      }
    }, (e) => {
      console.error('componentDidMount findVipCardNo error', e);
    });
  };

  setupCoupon = (vip) => {
    const shopId = vip.shopId;
    fetchCouponCode(shopId, { filter: { card_id: vip.card_id || vip.card_no, status: 1 } }).then((data) => {
      const meta = data.meta;
      if (meta && meta.totalCount > 0) {
        this.setState({
          couponCodeNum: meta.totalCount,
        });
      }
    }, (e) => {
      console.error('setupCoupon error', e);
    });
  };

  setupExtraInfo = (vip) => {
    const { shopId, card_id } = vip;
    Promise.all([fetchSavelist(shopId, card_id), fetchJc(shopId, card_id), fetchStored(shopId, card_id)]).then((values) => {
      // 储值
      let savelist = 0;
      if (values[0] && values[0].data) {
        savelist = values[0].data.amount || 0;
      }
      // 寄存
      let jc = 0;
      if (values[1] && values[1].data) {
        jc = values[1].data.amount || 0;
      }
      // 计次
      let stored = 0;
      if (values[2] && values[2].data && values[2].data.length) {
        stored = values[2].data[0].ret_num || 0;
      }
      this.setState({
        extraInfo: {
          savelist,
          jc,
          stored,
        },
      });
    });
  };

  changeRoute = (route) => {
    this.setState({
      route,
    });
  };

  returnHome = () => {
    this.setState({
      route: '',
    });
  };
  
  dofetchBranchList = (shopId, lng, lat) => {
    return new Promise((resolve, reject) => {
      fetchVipCardBranch(shopId).then((result) => {
        console.log(result)
        if (_.isNil(result.data) || _.isEmpty(result.data)) {
          resolve([]);
          return;
        }
        let resultList = [...(_.uniqBy(result.data, 'branch_no'))];
        // 本方法不再使用地理位置
        // if (lng && lat) {
        //   const pointA = new BMap.Point(lng, lat);
        //   resultList = resultList.map((item) => {
        //     if (item.location) {
        //       const pointB = new BMap.Point(item.location['0'], item.location['1']);
        //       item.distance = map.getDistance(pointA, pointB);
        //     } else {
        //       item.distance = defaultDistance;
        //     }
        //     return item;
        //   });
        //   resultList.sort((a, b) => {
        //     return a.distance - b.distance;
        //   });
        // }
        resolve(resultList);
      }, (error) => {
        reject(error);
      });
    });
  };

  updateBranchList = (branchList) => {
    if (branchList && branchList.length) {
      const geolocation = new BMap.Geolocation();
      const that = this;
      geolocation.getCurrentPosition(function (res) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS && res.accuracy) {
          const lng = res.point.lng;
          const lat = res.point.lat;
          if (lng && lat) {
            const pointA = new BMap.Point(lng, lat);
            const newBranchList = branchList.map((item) => {
              if (item.location) {
                const pointB = new BMap.Point(item.location['0'], item.location['1']);
                item.distance = map.getDistance(pointA, pointB);
              } else {
                item.distance = defaultDistance;
              }
              return item;
            });
            newBranchList.sort((a, b) => {
              return a.distance - b.distance;
            });
            that.setState({
              branchList: newBranchList,
            });
          }
        }
      }, { enableHighAccuracy: true });
    }
  };

  setupBranchList = (useGeo = false) => {
    useGeo = false; // 本方法不再使用地理位置
    return new Promise((resolve, reject) => {
      const shopId = this.props.location.query.shopId;
      if (shopId) {
        if (useGeo) {
          // const geolocation = new BMap.Geolocation();
          // const that = this;
          // geolocation.getCurrentPosition(function (res) {
          //   if (this.getStatus() == BMAP_STATUS_SUCCESS && res.accuracy) {
          //     resolve(that.dofetchBranchList(shopId, res.point.lng, res.point.lat));
          //   } else {
          //     resolve(that.dofetchBranchList(shopId));
          //   }
          // }, { enableHighAccuracy: true });
        } else {
          resolve(this.dofetchBranchList(shopId));
        }
      } else {
        resolve();
      }
    });
  };

  setupVipState = (shopId, cardId, vip) => {
    if (vip) {
      this.setState({
        isBind: true,
        vipInfo: vip,
        card_no: vip.card_no || '',
        card_id: vip.card_id || '',
        card_type: vip.card_type || '',
      });
    }
    
    // 获取消费记录
    cardId = '16805167202'
    fetchVipConsume(shopId, cardId).then((result) => {
      if (_.isNil(result.data) || _.isEmpty(result.data)) return;
      this.setState({
        vipConsume: result.data,
      });
    });
    fetchVipAcc(shopId, cardId).then((result) => {
      console.log('vipAcc', result)
      if (_.isNil(result.data) || _.isEmpty(result.data)) return;
      this.setState({
        vipAcc: result.data,
      });
    });
  };

  setupVipCardInfo = (shopId) => {
    fetchVipCardInfo(shopId).then((result) => {
      if (_.isNil(result.data) || _.isEmpty(result.data)) return;
      const vipCardInfo = result.data[0];
      this.setState({
        vipCardInfo,
      });
      if (vipCardInfo.bindExpiration !== undefined) {
        if (vipCardInfo.bindExpiration > 0) {
          this.setExpiration(vipCardInfo.bindExpiration);
        } else {
          this.clearExpiration();
        }
      }
    });

    fetchVipTypes(shopId).then((res) => {
      if (_.isArray(res.data) && res.data.length > 0) {
        this.setState({
          cardType: res.data,
        });
      }
    })
  };

  bind = () => {
    const shopId = this.props.location.query.shopId;
    const debugMode = !!this.props.location.query.__debug;
    if (!shopId) {
      return Toast.fail('没有连锁店编号');
    }
    this.props.form.validateFields((error, value) => {
      if (error) {
        const messages = _.map(error, (v) => {
          return v.errors[0].message;
        });
        Toast.fail(messages[0]);
        return;
      }
      if (value.phone) {
        value.phone = value.phone.replace(/\s/ig, '');
      }
      this.setState({
        loading: true,
      });
      /* 发起请求 */
      findVipCardNo(shopId, value.phone, '', '', value.code, value.saleman_id, debugMode)
        .then((data) => {
          console.log('VipCardNo', data)
          const vips = data.data.vips;
          if (vips && vips.length > 0) {
            if (vips.length === 1) {
              this.handleBindState(shopId, vips[0], value.saleman_id);
            } else {
              const selectorProps = {
                shopId,
                onClose: () => Popup.hide(),
                vips,
                onSelect: (index) => {
                  if (index > -1) {
                    this.handleBindState(shopId, vips[index], value.saleman_id);
                  }
                  Popup.hide();
                },
              };
              Popup.show(
                <CardSelector {...selectorProps} />
                , { maskProps, wrapClassName: 'cardSelector' });
            }
          } else {
            Toast.fail('手机号或卡号错误');
          }
          this.setState({
            loading: false,
          });
        }).catch((e) => {
          console.error('vipCard bind error', e);
          this.setState({
            loading: false,
          });
        });
    });
  };
  /*  */
  checkVipCompleteness = (checkVip) => {
    const checkCompleteness = (vip) => {
      const checkBirthday = (birthday) => {
        if (!birthday) {
          return false;
        }
        let birthdayVaild = false;
        const birth = moment(birthday);
        const now = moment();
        if (birth.isValid()) {
          const diff = now.diff(birth, 'years');
          if (diff >= -2 && diff <= 14) {
            birthdayVaild = true;
          }
        }
        return birthdayVaild;
      };

      let result = true;
      const { card_id, mobile, vip_tel, vip_name, birthday, vip_sex, vip_add } = vip;
      if ((!mobile && !vip_tel) || !vip_name || !birthday || !vip_sex) {
        result = false;
      }
      if (birthday && !checkBirthday(birthday)) {
        result = false;
      }
      return result;
    };

    const checkResult = checkCompleteness(checkVip);
    if (!checkResult) {
      Popup.show((
        <VipEditForm vip={checkVip} location={this.props.location} onClose={this.onPopupClose} onSubmit={this.onEditVip} />
      ), { animationType: 'slide-up', maskClosable: false });
    }
  };

  handleBindState = (shopId, vip, saleman_id) => {
    this.saveVip(vip);
    this.setState({
      card_no: vip.card_no,
      isBind: true,
      card_type: vip.card_type,

      card_id: vip.card_id,
      vipInfo: vip || {},
    }, () => {
      this.setupBigWheel();
    });

    this.setupVipState(shopId, vip.card_id, vip);
    this.setBindDate();

    this.setupExtraInfo(vip);
    this.setupIM(vip);

    let hyb_openid = this.state.openid || this.getLocalCache(CARD_OPENID);
    if (!hyb_openid || !hyb_openid.length || _.toUpper(hyb_openid) === 'NULL') {
      hyb_openid = '';
    }
    console.log("正在绑卡-----openid:", hyb_openid);
    bindVipCard({
      shopId,
      saleman_id,
      card_id: vip.card_id,
      card_no: vip.card_no,
      card_bind_status: true,
      hyb_openid,
    }).then((result) => {
      console.info('绑卡状态写入成功');
      // 检查会员资料完整性
      setTimeout(() => {
        this.checkVipCompleteness(vip);
      }, 2000);

      this.setupCoupon(vip);
    }, (error) => {
      console.error('绑卡状态写入失败', JSON.stringify(error));
    });
  };

  noAddSpace = (cardNo) => {
    cardNo = cardNo || '';
    let newCardNo = '';
    for (let i = 0; i < cardNo.length; i++) {
      newCardNo += cardNo.charAt(i);
      if (i % 4 === 3) {
        newCardNo += ' ';
      }
    }
    return newCardNo;
  };

  beginTimeLimit = () => {
    let seconds = 60;
    this.setState({
      timeLimit: seconds,
    });
    const timer = setInterval(() => {
      --seconds;
      this.setState({
        timeLimit: seconds,
      });
      if (seconds < 0) {
        clearInterval(timer);
        this.setState({
          timeLimit: 0,
          timer: 0,
        });
      }
    }, 1000);
    this.setState({
      timer,
    });
  };

  endTimeLimit = () => {
    setTimeout(() => {
      clearInterval(this.state.timer);
      this.setState({
        timeLimit: 0,
      });
    }, 1);
  }

  sendVerifyCode = () => {
    this.beginTimeLimit();
    if (this.state.timeLimit && +this.state.timeLimit > 0) {
      return;
    }

    const shopId = this.props.location.query.shopId;
    this.props.form.validateFields((error, value) => {
      if (value.phone) {
        const phone = value.phone.replace(/\s/ig, '');
        fetchVerifyCode(phone, shopId, { bind: true }).then(() => {
          Toast.success('验证码发送成功');
        }).catch((e) => {
          console.error(e);
          Toast.fail('获取验证码失败');
          this.endTimeLimit();
        });
      } else {
        Toast.info('请输入手机号');
        this.endTimeLimit();
      }
    });
  };

  sendAccCode = () => {
    if (this.state.timer || this.state.timeLimit) {
      return;
    }
    const shopId = this.props.location.query.shopId;
    const phone = this.state.vipInfo.mobile || this.state.vipInfo.vip_tel;
    fetchVerifyCode(phone, shopId, { type: '5' }).then(() => {
      this.beginTimeLimit();
      Toast.success('验证码发送成功');
    }).catch((e) => {
      Toast.fail('获取验证码失败');
    });
  };

  saveVip = (vip) => {
    const keepFields = ['openid', 'hyb_openid', 'shopId', 'card_no', 'card_id', 'mobile', 'vip_tel', 'phone', 'card_bind_status', 'saleman_id', 'card_type'];
    vip = _.pickBy(vip, (val, key) => {
      return _.includes(keepFields, key);
    });
    this.setLocalCache(CARD_NO, vip);
    this.setLocalCache(CARD_OPENID, vip.hyb_openid);
  };

  expireVip = () => {
    this.setLocalCache(CARD_NO_EXPIRE, this.getLocalCache(CARD_NO));
    this.handleDestroyBind(true);
  };

  handleDestroyBind = (removeBindStatus) => {
    if (removeBindStatus) {
      const vip = this.state.vipInfo || {};
      bindVipCard({
        shopId: vip.shopId,
        card_id: vip.card_id,
        card_no: vip.card_no,
        card_bind_status: false,
      }).then((result) => {
        console.info('绑卡状态写入成功');
      }, (error) => {
        console.error('绑卡状态写入失败', JSON.stringify(error));
      }).then(() => {
        this.removeLocalCache(CARD_NO);
        this.removeLocalCache(CARD_BIND_DATE);
        this.removeLocalCache(CARD_EXPIRATION);
        this.removeLocalCache(CARD_OPENID);
        const [head, tail] = window.location.href.split('?');
        window.location.href = head + '?' + tail.split('&').filter(p => p.startsWith('shopId=')).join('&');
        window.location.reload();
      });
    } else {
      this.removeLocalCache(CARD_NO);
      this.removeLocalCache(CARD_BIND_DATE);
      this.removeLocalCache(CARD_EXPIRATION);
      this.removeLocalCache(CARD_OPENID);
      const [head, tail] = window.location.href.split('?');
      window.location.href = head + '?' + tail.split('&').filter(p => p.startsWith('shopId=')).join('&');
      window.location.reload();
    }
  };

  fetchCardImageUrl = () => {
    const vipCardInfo = this.state.vipCardInfo;
    const card_type = this.state.card_type;
    let result = vipCardInfo ? vipCardInfo.cardImageUrl : '';
    if (vipCardInfo && vipCardInfo.vipTypes && vipCardInfo.vipTypes.length && card_type) {
      const vipType = _.find(vipCardInfo.vipTypes, (typeObj) => {
        return typeObj.id === card_type;
      });
      if (vipType && vipType.cardImageUrl) {
        result = vipType.cardImageUrl;
      }
    }
    return result;
  };

  onPopupClose = () => {
    Popup.hide();
  };
  
  // 注册新会员
  onSubmitVipReg = (data) => {
    data = data || {};
    data.shopId = data.shopId || this.props.location.query.shopId;
    data.code = data.code || 0;
    // 注册的同时也进行绑卡
    data.card_bind_status = true;
    data.card_bind_time = new Date();
    data.card_bind_saleman = data.saleman_id || '';
    data.vip_add = data.vip_add || '';
    delete data.branchName;
    delete data.branch_name;
    this.setState({
      regLoading: true,
    });

    data.openid = this.state.openid;
    data.debugData = JSON.stringify({
      url: window.location.href,
    });
   
    // reg
    regNew(data).then((result) => {
      const vip = result.data;
      if (vip) {
        console.log('newVip', vip );
        if (vip.isPaidVip) {
          const payData = {
            openid: this.state.openid,
            shopId: vip.shopId,
            branchId: vip.branchId || vip.branch_no,
            mobile: vip.mobile,
            cardType: vip.cardType,
          };
          paidVipUtil.doWxJsPay(payData).then((res) => {
            if (res && res.success) {
              this.saveVip(vip);
              Toast.success('注册成功，准备跳转...', 3);
              setTimeout(() => {
                window.location.reload();
              }, 500);
              this.returnHome();
            } else {
              Toast.fail('付费会员支付失败!');
            }
          }, (error) => {
            console.error(error);
          });
        } else {
          this.saveVip(vip);
          Toast.success('注册成功，准备跳转...', 3);
          setTimeout(() => {
            window.location.reload();
          }, 500);
          this.returnHome();
        }
      }
    }, (error) => {
      Toast.fail(_.map(error, (v) => {
        return _.get(v, 'errors[0].message');
      })[0], 3);
    }).then(() => {
      this.setState({
        regLoading: false,
      });
    });
  };

  onEditVip = (data) => {
    data = data || {};
    data.shopId = data.shopId || this.props.location.query.shopId;
    vipEdit(data).then((result) => {
      Popup.hide();
      this.saveVip(result.data);
      Toast.success('更新成功，准备刷新...', 3);
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    }, (error) => {
      Toast.fail(_.map(error, (v) => {
        return _.get(v, 'errors[0].message');
      })[0]);
    });
  };

  onRegVip = (needChangeRoute = true) => {
    let branchListPromise;
    if (this.state.branchList && this.state.branchList.length) {
      branchListPromise = Promise.resolve(this.state.branchList);
    } else {
      branchListPromise = this.setupBranchList(false);
    }
    branchListPromise.then((branchList) => {
      this.setState({
        branchList,
      });
      if (branchList && branchList.length) {
        setTimeout(() => {
          this.updateBranchList(branchList);
        }, 50);
      }
    }, (error) => {
      console.error('onRegVip', error);
      Toast.fail('分店获取失败，请稍后再试');
    });

    if (needChangeRoute) {
      this.changeRoute(ROUTE_REG);
    }
  };

  onSubmtFeedback = (data) => {
    data.shopId = data.shopId || (this.props.location.query.shopId);
    createConsumeFeedback(data.shopId, data);
    this.returnHome();
  };

  renderCoupon = () => {
    const couponOpts = {
      showBarcode: true,
      shopId: this.props.location.query.shopId,
      card_id: this.state.vipInfo.card_id,
      card_no: this.state.vipInfo.card_no,
    }
  /*  const couponOpts = {
      showBarcode: true,
      shopId: 'sixun_000153',
      card_id: 16805167202,
      card_no: 16805167202,
    } */
    return (
      <Container className="couponContainer" title="优惠券" navOption={{ onLeftClick: this.returnHome }}>
        <CouponCode {...couponOpts} />
      </Container>
    );
  };

  renderBarcode = () => {
    const barCodeOpts = {
      shopName: this.state.vipInfo.shopName,
      card_id: this.state.vipInfo.card_no || this.state.vipInfo.card_id,
    };

    return (
      <VipBarcode {...barCodeOpts} />
    );
  };

  renderVipRights = () => {
    const opts = {
      vipType: this.state.vipType,
      vipRights: this.state.vipRights
    };
    return (
      <Container className="vipRightsContainer" title="会员权益" navOption={{ onLeftClick: this.returnHome }}>
        <VipRights {...opts} />
      </Container>
    );
  };

  renderRegForm = () => {
    return (
      <Container className="vipRegContainer" title="注册新会员" navOption={{ onLeftClick: this.returnHome }}>
        <VipRegForm
          openid={this.state.openid}
          loading={this.state.regLoading}
          location={this.props.location}
          branchList={this.state.branchList}
          onSubmit={this.onSubmitVipReg}
          closable={false}
          salemanId={this.state.regSalemanId}
          branchNo={this.state.regBranchNo}
        />
      </Container>
    );
  };

  renderHelmet = () => {
    return (<Helmet>
      <script src="http://cdn.ronghub.com/RongIMLib-2.3.4.min.js" />
      <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" />
      <meta httpEquiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
      <meta httpEquiv="Pragma" content="no-cache" />
      <meta httpEquiv="Expires" content="0" />
      <title>{"会员卡"}</title>
      <style>{'html, body, #root { height: 100%; background: white; }'}</style>
    </Helmet>);
  };

  renderCard = () => {
    let cardTypeName = '';
    if (this.state.cardType.length > 0) {
      for (let x of this.state.cardType) {
        if (x.type_id == this.state.card_type) {
          cardTypeName = x.type_name;
        }
      }
    }

    const renderCardImage = () => {
      let cardImageUrl = this.fetchCardImageUrl();

      if (!(_.isString(cardImageUrl) && cardImageUrl.length > 0)) {
        cardImageUrl = require('../assets/new/card2.png');
      }

      return (

        /* 这里编写头部 */
        <div style={{ position: 'relative', padding: '0 .35rem', borderSizing:'border-box' }}>
          {/* <div className={styles.cardInfo}>
            <span className={styles.csn}>{this.state.shopName}</span>
            <span className={styles.cst}>电子会员卡</span>
          </div> */}
          <div className={styles.vipCardNo}>
            <span className={styles.vipType1}>{cardTypeName}</span>
            {/* <span className={styles.vipCardNo1}>卡号：</span> */}
            <span className={styles.vipCardNo2}>{this.noAddSpace(this.state.card_no || this.state.card_id)}</span>
          </div>

          {/* cardImageUrl */}
          <img src={require('../assets/new/card2.png')} className={styles.vipCardBg} alt="" />
          <img src={require('../assets/new/logo.png')} className={styles.vipLogo} />
          {/* <img className={styles.cardCode} src={require('../assets/vipcard/card_code.png')} onClick={() => {
            //跳转到条形码页面
            hashHistory.push({
              pathname: '/vipcode',
              query: {
                card_id: this.state.vipInfo.card_no || this.state.vipInfo.card_id,
                shopName: this.state.shopName,
              }
            });
          }} /> */}
        </div>
      );
    };

    const renderRightContent = () => {
      if (this.props.location.query.shopId === '000002' || '000021') {
        return (
          <span
            onClick={() => Modal.alert('解绑', '确定解除绑定当前会员卡?', [
              { text: '取消', onPress: () => console.log('cancel') },
              { text: '确定', onPress: () => this.handleDestroyBind(true) },
            ])}
          >
            解绑
          </span>
        );
      }
    };

    const showTip = () => {
      Modal.alert('暂无内容', '更新中，敬请期待');
    };

    const renderTopItemRow = () => {
      let smsText = '';
      if (this.state.timeLimit > 0) {
        smsText = `等待${this.state.timeLimit}秒`;
      }

      /* 首页 */
      return (
        <div className={styles.topItemRow}>
          <Flex>
            <Flex.Item>
              <IconItem type="reservation" onClick={() => {
                const { shopId, card_no } = this.state.vipInfo;
                let [head, tail] = window.location.href.split('?');
                head = head.replace('third_vipCard', 'appointment');
                tail += `&card_no=${card_no}`;
                window.location.href = head + '?' + tail;
              }} />
            </Flex.Item>
            <Flex.Item>
              <IconItem type="barcode" onClick={() => {
                //跳转到条形码页面
                hashHistory.push({
                  pathname: '/vipcode',
                  query: {
                    card_id: this.state.vipInfo.card_no || this.state.vipInfo.card_id,
                    shopName: this.state.shopName,
                  }
                });
              }} />
            </Flex.Item>


            <Flex.Item>
              {/* <IconItem
                type="exchange"
                text={smsText}
                onClick={() => {
                  if (this.state.timeLimit <= 0) {
                    this.sendAccCode();
                  }
                }}
              /> */}
              {this.state.wheelDot &&
                <IconItem
                  type="wheel"
                  dot
                  onClick={() => {
                    if (this.state.wheelStatus === false) {
                      Toast.info("活动暂未开始，敬请期待");
                      return;
                    } else {
                      const shopId = this.props.location.query.shopId;
                      hashHistory.push({
                        pathname: 'wheelsurf/index',
                        query: {
                          card_id: this.state.card_id,
                          shopId: shopId,
                        },
                      })
                    }
                  }}
                />
              }

              {
                !this.state.wheelDot && <IconItem
                  type="wheel"
                  onClick={() => {
                    if (this.state.wheelStatus === false) {
                      Toast.info("抱歉，活动暂未开始");
                      return;
                    } else {
                      const shopId = this.props.location.query.shopId;
                      hashHistory.push({
                        pathname: 'wheelsurf/index',
                        query: {
                          card_id: this.state.card_id,
                          shopId: shopId,
                        },
                      })
                    }
                  }}
                />
              }
            </Flex.Item>
            <Flex.Item>
              <IconItem dot={!!this.state.newImFlag} type="consultant" onClick={() => {
                // TODO: 删除
                if (this.state.vipInfo) {
                  if (!this.state.imSender) {
                    Toast.fail('网络异常，请稍候再试');
                    return;
                  }
                  if (!this.state.imTarget) {
                    Toast.fail('您还没有导购');
                    return;
                  }
                  this.changeRoute(ROUTE_IM);
                  this.setState({
                    newImFlag: false,
                  });
                } else {
                  showTip();
                }
              }} />
            </Flex.Item>
          </Flex>
        </div>
      );
    };

    const renderBlankRow = () => {
      return (
        <div className={styles.blankRow} />
      );
    };

    const renderBodyItemRow0 = () => {
      return (
        <div>
        <div className={styles.rowWrap}>
          <div className={styles.rowItem} onClick={() => this.changeRoute(ROUTE_MYACC)}>
            <span>{this.state.vipAcc.remain_acc}</span>
            <span>我的积分</span>
          </div>
          <div className={styles.rowItem} onClick={() => this.changeRoute(ROUTE_COUPON)}>
            <span>{this.state.couponCodeNum}</span>
            <span>优惠券</span>
          </div>
          {/* onClick={() =>this.changeRoute(ROUTE_XIAO_FEI)} */}
          <div className={styles.rowItem} onClick={() =>this.changeRoute(ROUTE_XIAO_FEI)}>
            <span>{this.state.vipConsume.length}</span>
            <span>消费记录</span>
          </div>
          <div className={styles.rowItem}>
            <img src={require('../assets/vipcard/ele_card/linecode.png')} onClick={() => {
            //跳转到条形码页面
            hashHistory.push({
              pathname: '/vipcode',
              query: {
                card_id: this.state.vipInfo.card_no || this.state.vipInfo.card_id,
                shopName: this.state.shopName,
              }
            })}}
         />
            <span>会员条码</span>
          </div>
        </div>

        <div className={styles.rowWrap2} onClick={() => this.changeRoute(ROUTE_RIGHTS)}>
           <div className={styles.row2Item}>
             <span></span>
             <span>会员等级</span>
             <span>查看会员权益</span>
           </div>
           <div className={styles.row2Item}>
             <div className={styles.item2}>
               <img src={require('../assets/vipcard/ele_card/v1.png')} alt="v1" />
               <div>金卡</div>
            </div>
             <div className={styles.rowLine}>
               <span></span>
             </div>
             <div className={styles.item2}>
               <img src={require('../assets/vipcard/ele_card/v2.png')} alt="v2" />
               <div>白金卡</div>
              </div>
             <div className={styles.rowLine}>
             <span></span>
             </div>
             <div className={styles.item2}>
               <img src={require('../assets/vipcard/ele_card/v3.png')} alt="v3" />
               <div>钻石卡</div>
             </div>
           </div>
        </div>
      </div>
      )
    }

    const renderBodyItemRow1 = () => {
      const showExtraInfo = this.state.showExtraInfo;
      return (
        <div className={styles.bodyItemRow1}>
          <div style={{ marginTop: '20px' }}>
            <Flex>

              {/* AI测试 */}
              <Flex.Item>
                <IconItem type="ai" size="small" /* onClick={() => this.changeRoute(ROUTE_AI)}  *//>
              </Flex.Item>


              {/* 积分兑换 content={this.state.vipAcc.remain_acc} */}
              <Flex.Item>
                <IconItem type="acc" size="small" onClick={() => this.changeRoute(ROUTE_ACC)} />
              </Flex.Item>

              {/* 服务预约 */}
              <Flex.Item>
                <IconItem type="reservation" size="small" onClick={() => {
                  const { shopId, card_no } = this.state.vipInfo;
                  let [head, tail] = window.location.href.split('?');
                  head = head.replace('third_vipCard', 'appointment');
                  tail += `&card_no=${card_no}`;
                  window.location.href = head + '?' + tail;
                }} />
              </Flex.Item>

              {/* 幸运抽奖 */}
              <Flex.Item>
                {
                  !this.state.wheelDot && <IconItem
                    type="wheel"
                    size="small"
                    onClick={() => {
                      if (this.state.wheelStatus === false) {
                        Toast.info("抱歉，活动暂未开始");
                        return;
                      } else {
                        const shopId = this.props.location.query.shopId;
                        hashHistory.push({
                          pathname: 'wheelsurf',
                          query: {
                            card_id: this.state.card_id,
                            shopId: shopId,
                          },
                        })
                      }
                    }}
                  />
                }
              </Flex.Item>


              {/* 优惠券 */}
              {/* <Flex.Item>
              <IconItem type="coupon" size="small" onClick={() => this.changeRoute(ROUTE_COUPON)} content={`${this.state.couponCodeNum}张可用`} />
            </Flex.Item> */}


              {/*  <Flex.Item>
              {
                showExtraInfo && <IconItem type="savelist" size="small" content={`${(+this.state.extraInfo.savelist).toFixed(2)}元`} />
              }
            </Flex.Item> */}

            </Flex>

            <Flex>
              {/* 附近门店  content={this.state.extraInfo.stored}*/}
              <Flex.Item onClick={() => {
                  hashHistory.push({
                    pathname: '/shopsDistance',
                    query: {
                      shopId: this.state.vipInfo.shopId,
                      card_id: this.state.vipInfo.card_id,
                    }
                  });
                }}>
                <IconItem type="stored" size="small" />
              </Flex.Item>
              {/* 专属顾问 */}
              <Flex.Item>
                <IconItem dot={!!this.state.newImFlag}
                  type="consultant"
                  size="small"
                  onClick={() => {
                    // TODO: 删除
                    if (this.state.vipInfo) {
                      if (!this.state.imSender) {
                        Toast.fail('网络异常，请稍候再试');
                        return;
                      }
                      if (!this.state.imTarget) {
                        Toast.fail('您还没有导购');
                        return;
                      }
                      this.changeRoute(ROUTE_IM);
                      this.setState({
                        newImFlag: false,
                      });
                    } else {
                      showTip();
                    }
                  }} />
              </Flex.Item>

              {/* 会员资料 */}
              <Flex.Item>
              <IconItem type="info" size="small" onClick={() => {
                  hashHistory.push({
                    pathname: '/vipcardinfo',
                    query: {
                      shopId: this.state.vipInfo.shopId,
                      phone: this.state.vipInfo.mobile || this.state.vipInfo.vip_tel || this.state.vipInfo.phone,
                      card_no: this.state.vipInfo.card_no,
                      card_id: this.state.vipInfo.card_id,
                    }
                  });
                }} />
              </Flex.Item>

              {/* 邀请注册 */}
              <Flex.Item>
                <IconItem type="invite" size="small" onClick={() => {
                  hashHistory.push({
                    pathname: '/vipinvite',
                    query: {
                      shopId: this.state.vipInfo.shopId,
                      phone: this.state.vipInfo.mobile || this.state.vipInfo.vip_tel || this.state.vipInfo.phone,
                      card_no: this.state.vipInfo.card_no,
                      card_id: this.state.vipInfo.card_id,
                    }
                  });
                }}/>
              </Flex.Item>
            </Flex>
          </div>
        </div>
      );
    };

    return (
      <Container title="电子会员卡" navOption={{ iconName: null, rightContent: renderRightContent() }}>
        <WhiteSpace size="lg" />
        <WingBlank>
          {/* 顶部卡 */}
          {renderCardImage()}
        </WingBlank>


        <WingBlank>
          {/* 顶部卡 */}
          {renderBodyItemRow0()}
        </WingBlank>

        <WingBlank>

        </WingBlank>

        <WingBlank>
          {renderBodyItemRow1()}
        </WingBlank>

        <WingBlank>
          {/* {renderBodyItemRow2()} */}
        </WingBlank>

        <WingBlank>
          {/* { renderTailItemRow() } */}
        </WingBlank>

        <WhiteSpace size="lg" />
        <WhiteSpace size="lg" />

        {/* <div style={{ textAlign: "center", marginTop: 10 }}>最近消费记录</div>

        <VipShopShow ref={el => (this.consumeRef = el)} vipConsume={this.state.vipConsume} /> */}

      </Container>
    );
  };

  renderVipReg = () => {
    const shopId = this.props.location.query.shopId;
    if (shopId) {
      return (
        <div>
          <Button type="ghost" className={styles.regBtn} onClick={this.onRegVip}>注册新会员</Button>
        </div>
      );
    }
  };

  renderBindInput = () => {
    const { getFieldProps } = this.props.form;
    let cardImgClass = 'bindCardImg';
    let imgUrl = this.fetchCardImageUrl();
    if (imgUrl) {
      cardImgClass += ' customCardImg';
    } else {
      imgUrl = require("../assets/new/card2.png");
    }
    return (
      <div className="bindWrapper">
        <div className="bindWrapperInner">
          <div className={styles.cardcss}>
            <div style={{position: 'relative'}}>
            {/* imgUrl */}
            <img src={ require("../assets/new/card2.png")} className={styles.cardImg} alt="" />
            <img src={require('../assets/new/logo.png')} className={styles.vipLogo} />
            <h3 className={styles.bindCardTitle}>白金卡</h3>
            </div>
          </div>

          <div className="bindBody">
            <InputItem
              {...getFieldProps('phone', {
                rules: [{ required: true, message: '请输入手机号' }],
              })}
              type="phone"
              placeholder="请输入手机号"
              className={styles.inputItem}
            >
            </InputItem>

            <div className={styles.inputItem} >
              <div className={styles.codeInputWrapper}>
                <InputItem
                  {...getFieldProps('code', {
                    rules: [{ required: true, message: '请输入验证码' }],
                  })}
                  type="number"
                  placeholder="请输入验证码" 
                >
                </InputItem>
              </div>

              <div className={styles.codeBtnWrapper}>
                <Button
                  onClick={this.sendVerifyCode} className="codeBtn" type="primary"
                  disabled={this.state.timeLimit > 0}
                >
                  {this.state.timeLimit > 0 ? '请等待' + this.state.timeLimit + '秒' : '获取验证码'}
                </Button>
              </div>
            </div>
            <div style={{ clear: 'both' }} />

            <InputItem
              {...getFieldProps('saleman_id', {
                rules: [],
              })}
              type="text"
              placeholder="请输入导购工号（选填）"
              className={styles.inputItem}
            >
            </InputItem>

            <div style={{height: '.966184rem'}}></div>
            <Button
              type="ghost" className={styles.bindBtn} onClick={this.bind}
              loading={this.state.loading}
            >老客绑卡</Button>
            <WhiteSpace size="lg" />
            {this.renderVipReg()}
          </div>
          <div className={styles.vipFormPush}></div>
        </div>

        <div className={styles.footerWrap}>
          <div className={styles.footerTitle}>
            <span></span>
            <span>绑卡有礼</span>
            <span></span>
          </div>
          <div className={styles.footerInfo}>
            <div className={styles.footItem1}>老客首次绑定会员卡，可获得以下奖励</div>
            <div className={styles.footItem2}>
              <span>满29减10优惠券×1</span>
              <span>5元全场通用券×2</span>
            </div>
          </div>
        </div>
        {/* <img src={require("../assets/vipcard/feet.jpg")} className={styles.footer} alt="" /> */}
      </div>
    );
  };

  renderFeedback = () => {
    return (
      <Container className={styles.feedback} title="电子会员卡" navOption={{ onLeftClick: this.returnHome }}>
        <ConsumeFeedback
          location={this.props.location}
          onSubmit={this.onSubmtFeedback}
        />
      </Container>
    );
  };

  renderImMessage = () => {
    const target = this.state.imTarget || {};
    const title = `专属顾问-${target.username}`;
    return (
      <Container className={styles.imMessage} title={title} navOption={{ onLeftClick: this.returnHome }}>
        <ChatMessage
          sender={this.state.imSender}
          target={this.state.imTarget}
          senderType={'vip'}
          messages={this.state.imMessages}
          onSendMessage={this.onSendIM}
          onReadMessage={(messageIds) => {
            const shopId = this.props.location.query.shopId;
            imService.readImMessage(shopId, messageIds);
          }}
        />
      </Container>
    );
  };

  renderVipAcc = () => {
    const accOpts = {
      remainAcc: this.state.vipAcc.remain_acc,
      data: this.state.ConvertAcc
    };
    return (
      <Container className={styles.accList} title="积分兑换" navOption={{ onLeftClick: this.returnHome }}>
        <VipAccList {...accOpts} />
      </Container>
    );
  };

  //消费记录
  renderVipXiaoFei = () => {
    return (
      <Container className={styles.accList} title="消费记录" navOption={{ onLeftClick: this.returnHome }}>
        <VipShopShow ref={el => (this.consumeRef = el)} vipConsume={this.state.vipConsume} />
      </Container>
    )
  }


 // 我的积分
 renderMyAcc = () => {
  
   /* const opt = {
     remainAcc: this.state.vipAcc.remain_acc,
      accList: [
        {
          acc_id: 1,
          oper_des: '活动积分',
          acc_num: 300,
          ope_date: '2017-12-16 17：02：09'
        },
        {
          acc_id: 2,
          oper_des: '购买积分',
          acc_num: 300,
          ope_date: '2017-12-16 17：02：09'
        }
      ]
   } */
    
  // 原积分数据
   const opt = {
    remainAcc: this.state.vipAcc.remain_acc,
    accList: this.state.vipAcc.acc_list,
  };
   return (
    <Container className={styles.accList} title="我的积分" navOption={{ onLeftClick: this.returnHome }}>
      <VipMyAcc {...opt} ></VipMyAcc>
    </Container>
   )
 }

  render() {
    let child;
    if (this.state.isBind) {
      switch (this.state.route) {
        case ROUTE_BARCODE:
          // child = this.renderBarcode();

          hashHistory.push({
            pathname: '/vipcode',
            query: {
              card_id: this.state.vipInfo.card_no || this.state.vipInfo.card_id,
              shopName: this.state.shopName,
            }
          });

          break;

        case ROUTE_RIGHTS:
          child = this.renderVipRights();
          break;

        case ROUTE_COUPON:
          child = this.renderCoupon();
          break;

        case ROUTE_FEEDBACK:
          child = this.renderFeedback();
          break;

        case ROUTE_IM:
          child = this.renderImMessage();
          break;

        case ROUTE_ACC:
          child = this.renderVipAcc();
          break;

        case ROUTE_XIAO_FEI:
          child = this.renderVipXiaoFei();
          break;
        case ROUTE_AI:
          child = this.renderTestAi();
          break;

        case ROUTE_MYACC:
          child = this.renderMyAcc();
          break;
        default:
          child = this.renderCard();
          break;
      }
    } else {
      switch (this.state.route) {
        case ROUTE_REG:
          child = this.renderRegForm();
          break;

        default:
          child = this.renderBindInput();
          break;
      }
    }

    return (
      <div className={styles.vipCardContainer}>
        {this.renderHelmet()}
        {child}
      </div>
    );
  }
}

export default createForm()(VipCard);
